<?php

namespace App\Services;

use App\Models\Hall;
use App\Models\HallConfig;
use App\Models\HallDomain;
use common\enum\CommonEnum;
use common\enum\MasterLogEnum;
use common\utils\SysCode;
use Illuminate\Support\Facades\DB;

class GlobalMaintainService
{

    /**
     * 维护厅主表单
     * @param array $values
     * @return array
     */
    public static function getHalllist(array $values)
    {

        $domain = HallDomain::select("hall_id")->selectRaw("GROUP_CONCAT(domain) as domain");
        $select = ['a.id', 'a.company_name', 'a.admin_name', 'b.status', 'b.start_time','b.end_time','c.domain'];
        $query  = DB::table('hall as a')
            ->leftJoin('hall_config as b', 'b.hall_id', '=', 'a.id')
            ->joinSub($domain, 'c','c.hall_id','=','a.id','LEFT')
            ->select($select);
        if (!empty($values['hall_id'])) {
            $query->where(['a.id' => $values['hall_id']]);
        }
        $page = $values['page'] ?? CommonEnum::PAGE_DEFAULT;
        $size = $values['page_size'] ?? CommonEnum::PAGE_SIZE_TWENTY;
        return  get_page_data($query, $page, $size);
    }


    /**
     * 维护时间
     * @param $hallId
     * @param $time
     * @return mixed
     * @throws \App\Exceptions\CustomException
     */
    public static function maintainTime($hallId, $time)
    {
        //时间为null，维护中的厅主回到设置前的状态
        if (empty($time['start_time']) && empty($time['end_time'])) {
            HallConfig::whereIn('hall_id', $hallId)->where(['status' => CommonEnum::MAINTAIN])->update(['status' => DB::raw('pre_status')]);
        }
        $result = HallConfig::whereIn('hall_id', $hallId)->update($time);
        if (!$result) {
            error_exit(SysCode::FAILED);
        }
        //设置维护时间写入日志
        $hall = Hall::select(['company_name'])->whereIn('id', $hallId)->get()->toArray();
        $res = array_reduce($hall, function ($result, $value) {
            return array_merge($result, array_values($value));
        }, array());
        $remark = str_replace(['{:name}', '{:star_time}', '{:end_time}'], [implode('、',$res),$time['start_time'], $time['end_time']], MasterLogEnum::REMARK['maintain_time_setting']);
        MasterLogService::writeMasterLog(MasterLogEnum::MAINTAIN_EDIT_TIME, MasterLogEnum::SUCCESS, $remark);
        return $result;
    }
}
